/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.execute.controller;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.AttachmentRequestContentTypeEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteFilesRecordDto;
import com.icinfo.cloud.provider.punish.execute.dto.FilePreviewAddressDto;
import com.icinfo.cloud.provider.punish.execute.dto.FileUrlDto;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteFilesRecordService;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.web.BaseController;
import com.icinfo.framework.tools.utils.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * 描述: 裁执分离文件记录表 execute_files_record 对应的Controller类.<br>
 *
 * @author framework generator
 * @date 2022年08月24日
 */
@RestController
@RequestMapping("/files")
public class ExecuteFilesRecordController extends BaseController {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(ExecuteFilesRecordController.class);

    @Autowired
    private IExecuteFilesRecordService executeFilesRecordService;

    /**
     * 描述: 获取法院文件信息，回调接口，主要是地址实时获取url
     *
     * @param executeId 此裁执分离唯一id
     * @return com.icinfo.framework.common.web.Result
     * @author zhanghongqiang
     * @Date 2022/9/6
     */
    @GetMapping("/readExecuteFilesList")
    @ApiOperation(value = "获取法院文件信息", httpMethod = "GET")
    public Result<List<ExecuteFilesRecordDto>> readExecuteFilesList(@RequestParam("executeId") String executeId) {
        List<ExecuteFilesRecordDto> filesList = executeFilesRecordService.getExecuteFilesList(executeId);
        return Result.success(Constant.STRING_GET_SUCCESS, filesList);
    }

    /**
     * 描述: 获取法院文件地址详情信息
     *
     * @param filePreviewAddressDto
     * @return com.icinfo.framework.common.web.Result<java.lang.String>
     * @author zhanghongqiang
     * @Date 2022/9/6
     */
    @PostMapping("/readFilePreviewAddress")
    @ApiOperation(value = "获取法院文件地址详情信息", httpMethod = "POST")
    public Result<String> readFilePreviewAddress(@RequestBody @Validated FilePreviewAddressDto filePreviewAddressDto, HttpServletResponse response) throws Exception {
        String filePreviewAddress = executeFilesRecordService.getFilePreviewAddress(filePreviewAddressDto);
        if (StringUtils.isNotBlank(filePreviewAddress)) {
            return Result.success(Constant.STRING_GET_SUCCESS, filePreviewAddress);
        }
        return Result.error(Constant.STRING_GET_FAIL);
    }

    @ResponseBody
    @RequestMapping("/preview")
    public void findPdf(@RequestBody FileUrlDto fileUrlDto, HttpServletResponse response) throws Exception {
        String url = fileUrlDto.getUrl();
        if (StringUtils.isBlank(url)) {
            throw new BusinessException("未指定url路径");
        }
        String type = FileTypeUtil.getType(new URL(url).openStream());
        if (!type.equals(AttachmentRequestContentTypeEnum.pdf.getCode())){
            throw new BusinessException("仅支持pdf预览");
        }
        response.setContentType("application/pdf");
        File file = getFile(url);
        FileInputStream in = new FileInputStream(file);
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[512];
        while ((in.read(b)) != -1) {
            out.write(b);
        }
        out.flush();
        in.close();
        out.close();
    }

    /**
     * 描述: 将图片转为file
     *
     * @param url
     * @return java.io.File
     * @author zhanghongqiang
     * @Date 2022/9/19
     */
    public File getFile(String url) throws Exception {
        //对本地文件命名
        File file = null;
        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            String uuid = StringUtils.uuid();
            file = File.createTempFile("net_url", uuid + ".pdf");
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 【V1.12.1】描述: 根据文件地址获取文件流
     *
     * @param url
     * @param response
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/downloadFileByFileUrl")
    public void downloadFileByFileUrl(@RequestParam("url") String url, HttpServletResponse response) {
        if (StringUtils.isBlank(url)) {
            throw new BusinessException("未指定url路径");
        }

        ServletOutputStream out = null;
        try {
            //与服务器建立连接
            URL url1 = new URL(url);
            URLConnection conn = url1.openConnection();
            InputStream inputStream = conn.getInputStream();
            try {
                String fileType = FileTypeUtil.getType(new URL(url).openStream());
                if (ObjectUtil.isNotEmpty(fileType)) {
                    fileType = fileType.toLowerCase();
                }
                String uuid = StringUtils.uuid();
                String fileName = uuid + "." + fileType;
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            } catch (Exception e){
                e.printStackTrace();
            }
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            inputStream.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}